/*
 * xmla.js, Dec 13, 2007
 */

/** Initilize XMLA connection. */
function xmlaInit() {
    var con = new OAT.Connection(OAT.ConnectionData.TYPE_XMLA);
    con.options.endpoint = $v("xmla_endpoint");
    con.options.dsn = $v("xmla_dsn");
    con.options.user = $v("user");
    con.options.password = $v("password");
    OAT.Xmla.connection = con;
}

/** select catalog(s) avaliable. */
function catalogOption() {
    // open dialog more than one time, a duplicated table will insert.
    var tbs = $("catalog_options").getElementsByTagName("table");
    // so remove it first.
    for (var i = tbs.length; i > 0; i--) {
        OAT.Dom.unlink(tbs[i]);
    }
    dialogs.catalogs = new OAT.Dialog("Select Catalog(s)", "catalog_options", {width:500,modal:1,buttons:1});
    $("catalog_options").style.display = "";
    OAT.Dom.attach("usecatalog", "click", function() {
        var opts = $("unselect_catalogs").getElementsByTagName("option");
        var select = $("select_catalogs");
        for (var i = 0; i < opts.length; i++) {
            if (opts[i].selected) {
                OAT.Dom.option(opts[i].value, opts[i].value, select);
                OAT.Dom.unlink(opts[i]);
            }
        }
    });
    OAT.Dom.attach("unusecatalog", "click", function() {
        var opts = $("select_catalogs").getElementsByTagName("option");
        var select = $("unselect_catalogs");
        for (var i = 0; i < opts.length; i++) {
            if (opts[i].selected) {
                OAT.Dom.option(opts[i].value, opts[i].value, select);
                OAT.Dom.unlink(opts[i]);
            }
        }
    });
    dialogs.catalogs.cancel = dialogs.catalogs.hide;
    dialogs.catalogs.ok = function () {
        xmlaTables();
    }
    dialogs.catalogs.show();
}

/** get all dsn(s) of xmla provider. */
function xmlaDSN() {
    xmlaInit();
    OAT.Xmla.discover(function(pole) {
        if (pole.length) {
            var select = $("xmla_dsn");
            OAT.Dom.clear(select);
            for (var i = 0; i < pole.length; i++) {
                OAT.Dom.option(pole[i], pole[i], select);
            }
            dialogs.connection.okBtn.removeAttribute("disabled");
        }
    });
}

/*------------------------------------------------------------------------*/
function dbSchemaCallback(pole) {
    var select = $("unselect_catalogs");
    var select_ns = $("catalog_ns");
    OAT.Dom.clear(select);
    OAT.Dom.clear(select_ns);
    OAT.Dom.option("Please Choose", "", select_ns);
    for (var i = 0; i < pole.length; i++) {
        OAT.Dom.option(pole[i], pole[i], select);
        OAT.Dom.option(pole[i], pole[i], select_ns);
    }
    if (!pole.length) {
        OAT.Dom.option("[No Catalog]", "", select);
    }
    catalogOption();
}

/** Get all data source cataloges. */
function xmlaDbSchema() {
    dialogs.connection.hide();
    xmlaInit();
    OAT.Xmla.dbschema(dbSchemaCallback);
}

/*-------------------------------------------------------------------*/
function xmlaTablesCallback(db_catalog) {
    var ds = new DataSource(db_catalog);
    var dbNode = globalVar.dbView.insertDb(ds);
    return function(catalog, pole) {
        var tables = pole[0];
        for (var i = 0; i < tables.length; i++) {
            var name = tables[i];
            var schema = pole[1][i];
            var nq = "";
            if (catalog && catalog != "")
                nq += catalog + ".";
            if (schema && schema != "")
                nq += schema + ".";
            nq += name;
            var tb = new Table(nq, name, statistic.table);
            var tbNode = globalVar.dbView.insertTable(dbNode, tb);
            statistic.table++;
            OAT.Xmla.primaryKeys(catalog, schema, name, function(data) {tb.primaryKeys = data;});
            OAT.Xmla.primaryKeys(catalog, schema, name, function(data) {tb.foreignKeys = data;});
            OAT.Xmla.columns(catalog, schema, name, xmlaColumnCallback(tb, tbNode));
            ds.addTable(tb);
        }
        globalVar.dbs.push(ds);
    }
}

function xmlaTables() {
    dialogs.catalogs.hide();
    var opts = $("select_catalogs").getElementsByTagName("option");
    for (var i = 0; i < opts.length; i++) {
        OAT.Xmla.tables(opts[i].value, xmlaTablesCallback(opts[i].value)); 
    }
}

/*--------------------------------------------------------------------*/

function xmlaColumnCallback(tb, tbNode) {
    return function(columns) {
        for (var i = 0; i < columns.length; i++) {
            var name = columns[i]['name'];
            var col = new Column(tb.uri + "." + name, name);
            tb.addColumn(col);
            interval.total += interval.loop;
            setTimeout(bind(globalVar.dbView.insertColumn, [tbNode, col]), interval.total);
            statistic.column++;
        }
        tbNode.collapse();
    }
}

////////////////////////////////////////////////////////////////////////
/* --------------- publish RDF data ------------------------------*/
var tmpTables = {};
function publishRdf() {
    dialogs.connection.hide();
    var width = Math.round(screen.width / 2);
    var height = Math.round(screen.height / 2);
    width = (width > 400) ? width : 400;
    height = (height > 200) ? height : 200;
    var win = new OAT.Window({close:1, min:0, max:0, width:width, height:height, title:"Publish RDF", magnetsH:2}, OAT.WindowData.TYPE_AUTO);
    $("pr_onto_prefix").value = saveOption.defaultOntoPrefix;
    $("pr_prop_prefix").value = saveOption.defaultPropPrefix;
    $("pr_iri_prefix").value = saveOption.defaultIRIPrefix;
    $("pr_iri_convert_rule").value = saveOption.constIRIStringPrefix;
    $("pr_btn_save").setAttribute("disabled", "disabled");
    $("pr_btn_generate").setAttribute("disabled", "disabled");
    $("pr_btn_next").onclick = publishRdfNext;
    win.onclose = function() {
        OAT.Dom.hide(win.div);
        OAT.Dom.unlink(win.div);
        OAT.Dom.show(globalVar.canvas);
    };
    $("pr_btn_cancel").onclick = win.onclose;
    $("pr_btn_save").onclick = function() {
        generateMapping(saveMapping);
        setTimeout(win.onclose(), 1000);
    }
    $("publish_rdf").style.display = "";
    win.content.appendChild($("publish_rdf"));
    document.body.appendChild(win.div);
    OAT.Dom.hide(globalVar.canvas);
    OAT.Dom.show(win.div);
    OAT.Dom.center(win.div, 1, 1)
}

/** wizard pages. */
var prNextState = "dbs"
function publishRdfNext() {
    if (prNextState == "dbs") {
        xmlaInit();
        OAT.Xmla.dbschema(function(data) {
            var tables = $("pr_ds_table");
            for (var i = 0; i < data.length; i++) {
                var newRow = tables.insertRow(i + 1);
                newRow.setAttribute("align", "center");
                var cell1 = newRow.insertCell(0);
                cell1.innerHTML = "<input type=\"checkbox\" />";
                var cell2 = newRow.insertCell(1);
                cell2.innerHTML = data[i];
            }
        });
        prNextState = "table";
        $("pr_config").style.display = "none";
        $("pr_data_sources").style.display = "";
        $("pr_tables").style.display = "none";
        $("pr_columns").style.display = "none";
    } else if (prNextState == "table") {
        var tables = $("pr_table_table");
        var rows = $("pr_ds_table").rows;
        for (var i = 1; i < rows.length; i++) {
            var cell1 = rows[i].cells[0];
            if (cell1.childNodes[0].checked) {
                var catalog = rows[i].cells[1].innerHTML;
                OAT.Xmla.tables(catalog, function(retCatalog, data) {
                    for (var j = 0; j < data[0].length; j++) {
                        var tbName = data[0][j];
                        var st = {
                            name: tbName,
                            ontology:"",
                            catalog: retCatalog,
                            schema: data[1][j],
                            iriClass:null,
                            columns:[]
                        };
                        tmpTables[tbName] = st;
                        var newRow = tables.insertRow(tables.rows.length);
                        newRow.setAttribute("align", "center");
                        var cell1 = newRow.insertCell(0);
                        cell1.innerHTML = "<input type=\"checkbox\" checked=\"checked\" />"
                        var cell2 = newRow.insertCell(1);
                        cell2.innerHTML = tbName;
                        var cell3 = newRow.insertCell(2);
                        cell3.innerHTML = "<input type=\"text\" value=\"" + data[0][j] + "\" />";
                        var cell4 = newRow.insertCell(3);
                        cell4.innerHTML = "";
                    }
                });
            }
        }
        prNextState = "column";
        $("pr_config").style.display = "none";
        $("pr_data_sources").style.display = "none";
        $("pr_tables").style.display = "";
        $("pr_columns").style.display = "none";
    } else if (prNextState == "column") {
        var rows = $("pr_table_table").rows;
        for (var i = 1; i < rows.length; i++) {
            var cell1 = rows[i].cells[0];
            if (cell1.childNodes[0].checked) {
                var tableName = rows[i].cells[1].innerHTML;
                var ontoName = rows[i].cells[2].childNodes[0].value;
                tmpTables[tableName].ontology = ontoName;
                tmpTables[tableName].iriClass = {
                    constIRI:true,
                    name:"",
                    conv:"",
                    primaryKey:null,
                    str:$("pr_iri_convert_rule").value + tableName + "#this"
                };
                var callback = function(table) {
                    return function(data) {
                        var tables = $("pr_columns_table");
                        for (var j = 0; j < data.length; j++) {
                            var newRow = tables.insertRow(tables.rows.length);
                            newRow.setAttribute("align", "center");
                            var cell1 = newRow.insertCell(0);
                            cell1.innerHTML = "<input type=\"checkbox\" checked=\"checked\" />"
                            var cell2 = newRow.insertCell(1);
                            cell2.innerHTML = data[j].name;
                            var cell3 = newRow.insertCell(2);
                            cell3.innerHTML = "<input type=\"text\" value=\"" + data[j].name + "\" />";
                            var cell4 = newRow.insertCell(3);
                            cell4.innerHTML = table;
                        }
                    }
                }
                OAT.Xmla.columns(tmpTables[tableName].catalog, tmpTables[tableName].schema, tableName, callback(tableName));
            }            
        }
        $("pr_btn_next").setAttribute("disabled", "disabled");
        $("pr_btn_save").removeAttribute("disabled");
        $("pr_btn_generate").removeAttribute("disabled");
        $("pr_config").style.display = "none";
        $("pr_data_sources").style.display = "none";
        $("pr_tables").style.display = "none";
        $("pr_columns").style.display = "";
    }
}

function generateMapping(callback) {
    // scan all columns
    var tables = {};
    var rows = $("pr_columns_table").rows;
    for (var i = 1; i < rows.length; i++) {
        var cell1 = rows[i].cells[0];
        if (cell1.childNodes[0].checked) {
            var tbName = rows[i].cells[3].innerHTML;
            var columnName = rows[i].cells[1].innerHTML;
            var propName = rows[i].cells[2].childNodes[0].value;
            if (tables[tbName]) {
                tables[tbName].columns.push({
                    column:columnName,
                    property:propName
                });
            } else {
                var st = {
                    table:tbName,
                    columns:[]
                };
                st.columns.push( {
                    column:columnName,
                    property:propName
                });
                tables[tbName] = st;
            }
        }
    }
    // construct mapping items  (so far, it's support simple mapping only). 
    for (var table in tables) {
        // table's qualified name and name
       var tbItem = tables[table];
        var nq = "";
        if (tmpTables[table].catalog && tmpTables[table].catalog != "")
            nq += tmpTables[table].catalog + ".";
        if (tmpTables[table].schema && tmpTables[table].schema != "")
            nq += tmpTables[table].schema + ".";
        nq += table;
        var newTable = new Table(nq, table, statistic.table);
        statistic.table += 1;
        var mappingTable = new MappingTable(newTable, statistic.mappingTable);
        statistic.mappingTable += 1;
        var ontoUri = saveOption.defaultOntoPrefix + tmpTables[table].ontology;
        var newOntology = new Ontology(ontoUri, tmpTables[table].ontotlogy);
        statistic.ontology += 1;
        var mappingOnto = new MappingOnto(newOntology, statistic.mappingOnto);
        statistic.mappingOnto += 1;
        mappingOnto.iriClass = tmpTables[table].iriClass;
        mappingOnto.hasIRIClass = true;
        mappingTable.addMappingOnto(mappingOnto);
        // all columns
        var columns = tbItem.columns;
        for (var i = 0; i < columns.length; i++) {
            var columnUri = nq + columns[i].column;
            var newColumn = new Column(columnUri, columns[i].column);
            statistic.column += 1;
            var mappingColumn = new MappingColumn(newColumn, statistic.mappingColumn);
            statistic.mappingColumn += 1;
            newTable.addColumn(newColumn);
            var propUri = saveOption.defaultPropPrefix + columns[i].property;
            var newProp = new Property(propUri, columns[i].property);
            statistic.property += 1;
            var mappingProperty = new MappingProperty(newProp, statistic.mappingProperty);
            statistic.mappingProperty += 1;
            mappingProperty.setMappingColumn(mappingColumn);
            mappingOnto.addMappingProperty(mappingProperty);
        }
        globalVar.mappingTables.push(mappingTable);
    } 
    if (typeof(callback) == "function") {
        callback();
    }
}
